function isEmptyStr(str) {
    return str === null || str === undefined || str.trim().length === 0;
}

/****************************
*Function name: checkUserName
*Description: Check whether the username meets the requirements.
*Parameters: username
*Return: state(true or false)
*******************************/
function checkUserName(userName) {
    if (!isEmptyStr(userName) && userName.length >= 4 && userName.length <= 10) {
        return true;
    } else {
        alert("Username should be 4~10 characters");
        return false;
    }
}




/****************************
*Function name: checkPwd
*Description: Check whether the password meets the requirements.
*Parameters: password
*Return: state(true or false)
*******************************/
function checkPwd(pwd) {
    if (!isEmptyStr(pwd) && pwd.length >= 5 && pwd.length <= 10) {
        return true;
    } else {
        alert("password should be 5~10 characters");
        return false;
    }
}

/****************************
*Function name: checkTwoPwds
*Description: Check whether the two passwords are the same.
*Parameters: password
*Return: state(true or false)
*******************************/
function checkTwoPwds(pwd1, pwd2) {
    if (!isEmptyStr(pwd1) && !isEmptyStr(pwd2) && pwd1 == pwd2) {
        return true;
    }
    else {
        alert("Passwords don't match");
        return false;
    }
}

/****************************
*Function name: checkTwoPwds
*Description: To sign up.Pass the username and password to the backend
*Parameters: null
*Return: null
*******************************/
function reg() {
    var userName = document.getElementById("userName").value;
    var pwd = document.getElementById("pwd1").value;
    var pwd2 = document.getElementById("pwd2").value;
    // console.log("?");
    if (checkUserName(userName) && checkPwd(pwd) && checkTwoPwds(pwd, pwd2)) {
        let data = { username: userName, pwd: pwd };
        function ok() {
            console.log(this.responseText);
            if (this.responseText == "success") {
                alert("Signup successfully!")
                location.replace('../html/login.html');
            } else {
                alert(this.responseText);
            }
        }
        function ko() {
            alert("Something wrong with signup!")
        }

        ajaxRequest("../php/signup.php", 'post', data, ok, ko);

    }

}

window.onload = function(){
    document.getElementById('submit_reg').onclick = reg;
}